package cbbx_sm.probabilistic_model;

import java.util.Vector;

import cbbx_sm.utils.Timestamp;

public class PastStatesList {
	private final int capacity;
	private Vector<SystemState> pastStates;
	
	public PastStatesList(int capacity){
		this.capacity = capacity;
		pastStates = new Vector<SystemState>(capacity);
		
		clear();
	}
	
	/**
	 * Insert a new state in the list, putting null in
	 * every location that is skipped.
	 * 
	 * @param state
	 */
	public void insertState(SystemState state){
		if (pastStates.get(0) == null){
			addWithoutExtending(state);
			return;
		}
		
		Timestamp lastTimestamp = null;
		for (int i = 0; i < pastStates.size(); i++){
			SystemState s = pastStates.get(i);
			if (s != null){
				lastTimestamp = s.getTimestamp();
				break;
			}
		}
		
		assert(state.getTimestamp().compareTo(pastStates.get(0).getTimestamp()) <= 0);
		
		// If this frame is very far in time, I shift the list...
		for (int i = 1; i < Timestamp.subtractTimestamps(state.getTimestamp(), lastTimestamp); i++)
			addWithoutExtending(null);	
		addWithoutExtending(state);
	}
	
	public void clear(){
		for (int i = 0; i < capacity; i++)
			pastStates.add(null);
	}
	
	/**
	 * Add a new state and remove the last if the list tail is 
	 * too long.
	 * 
	 * @param state
	 */
	private void addWithoutExtending(SystemState state){
		if (pastStates.size() == capacity)
			pastStates.remove(capacity - 1);
		pastStates.add(0, state);
	}
	
	public SystemState getSystemState(int index){
		return pastStates.get(index);
	}
	
	@Override
	public String toString(){
		StringBuffer str = new StringBuffer();
		str.append("PastStates(");
		for (int i = 0; i < capacity; i++)
			if (pastStates.get(i) != null)
				str.append("" + pastStates.get(i).toString() + ", ");
			else str.append("null, ");
		str.append(")");
		
		return str.toString();
	}
	
	
	// Getters & Setters
	
	public int getCapacity() {
		return capacity;
	}

	public Vector<SystemState> getPastStates() {
		return pastStates;
	}
}

